package com.windchime.blog.controller;

import com.windchime.blog.entity.Blog;
import com.windchime.blog.entity.Tag;
import com.windchime.blog.entity.Type;
import com.windchime.blog.service.BlogService;
import com.windchime.blog.service.TagService;
import com.windchime.blog.service.TypeService;
import com.windchime.blog.utils.StringSplitUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
import java.util.stream.Collectors;

@Controller
public class FrontBlogController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TagService tagService;

    @Autowired
    private TypeService typeService;

    /**
     * 博客详情
     * @param id 博客ID
     * @param model 传值
     * @return blog
     */
    @GetMapping("/blog/{id}")
    public String blogItem(@PathVariable Long id, Model model) {
        Blog blog = blogService.getBlogForConvert(id);

        /*
            设置该博客是什么分类
         */
        Type type = typeService.getById(blog.getTypeId());
        blog.setTypeName(type.getName());

        /*
            设置该博客有什么标签
         */
        String tagIds = blog.getTagIds();
        List<Long> tagIdList = StringSplitUtil.split(tagIds, ",");
        List<Tag> tags = tagIdList.stream().map(tagId -> tagService.getById(tagId)).collect(Collectors.toList());
        blog.setTags(tags);

        model.addAttribute("blog", blog);

        return "blog";
    }
}
